import { injectable, inject } from 'inversify'
import { PrismaDB } from '../db'
import { UserDto } from './user.dto'
import { plainToClass } from 'class-transformer'
import { validate } from 'class-validator'
import { JWT } from '../jwt'

@injectable()
export class UserService {
  constructor(
    @inject(PrismaDB) private readonly PrismaDB: PrismaDB,
    @inject(JWT) private readonly JWT: JWT // 依赖注入
  ) {}
  public async getList() {
    return await this.PrismaDB.prisma.user.findMany()
  }
  public async createUser(user) {
    let userDto = plainToClass(UserDto, user)
    const error = await validate(userDto)
    if (error.length) {
      return error
    } else {
      let result = await this.PrismaDB.prisma.user.create({
        data: userDto,
      })
      return  {
        ...result,
        token: this.JWT.createToken(result)
      }
     
    }
  }
}
